<?php

namespace App\Services\UsersBatchHandler;

use Closure;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class UsersBatchHandler
{
	/**
	 * @var [vip, normal, all]
	 */
	protected $scope;
	
	protected function init($scope)
	{
		$this->scope = in_array($scope, ['vip', 'normal', 'all']) ? $scope : 'vip';
	}
	
	protected function handle(Closure $closure)
	{
		User::query()
			->where('grade', $this->scope)
			->chunks(20, function (Collection $users) use ($closure) {
				
				if ($users->isEmpty()) return false;
				
				foreach ($users as $user) {
					$closure($user);
					Log::debug("User: {$user->id} handled.");
				}
				
				return true;
			}, 'desc');
	}
	
	public function run(Closure $closure, $scope = 'vip')
	{
		$this->init($scope);
		$this->handle($closure);
	}
}
